package com.rabbiter.oes.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbiter.oes.entity.MultiQuestion;
import com.rabbiter.oes.entity.PaperManage;
import com.rabbiter.oes.mapper.MultiQuestionMapper;
import com.rabbiter.oes.mapper.PaperMapper;
import com.rabbiter.oes.service.MultiQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 选择题
 */
@Service
public class MultiQuestionServiceImpl extends ServiceImpl<MultiQuestionMapper, MultiQuestion> implements MultiQuestionService {

    // 题目与试卷关系
    @Autowired
    private PaperMapper paperMapper;

    @Override
    public List<MultiQuestion> findByIdAndType(Integer paperId) {
        LambdaQueryWrapper<PaperManage> paperWrapper = Wrappers.lambdaQuery(PaperManage.class).eq(PaperManage::getQuestionType, 1).eq(PaperManage::getPaperId, paperId);
        List<PaperManage> paperManages = paperMapper.selectList(paperWrapper);
        if (CollectionUtil.isNotEmpty(paperManages)) {
            // 筛出题目id
            List<Integer> questionIds = paperManages.stream().map(PaperManage::getQuestionId).collect(Collectors.toList());
            // 查出题目信息
            return baseMapper.selectBatchIds(questionIds);
        }
        return new ArrayList<MultiQuestion>();
    }

    @Override
    public IPage<MultiQuestion> findAll(Page<MultiQuestion> page) {
        return baseMapper.selectPage(page, Wrappers.lambdaQuery(MultiQuestion.class));
    }

    @Override
    public MultiQuestion findOnlyQuestionId() {
        LambdaQueryWrapper<MultiQuestion> wrapper = Wrappers.lambdaQuery(MultiQuestion.class).orderByDesc(MultiQuestion::getQuestionId);
        List<MultiQuestion> multiQuestions = baseMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(multiQuestions)) {
            return multiQuestions.get(0);
        }else {
            MultiQuestion multiQuestion = new MultiQuestion();
            multiQuestion.setQuestionId(1);
            return multiQuestion;
        }

    }

    @Override
    public Integer add(MultiQuestion multiQuestion) {
         baseMapper.insert(multiQuestion);
         return multiQuestion.getQuestionId();
    }

    @Override
    public List<Integer> findBySubject(Integer pageNo) {
        return baseMapper.findBySubject(pageNo);
    }

    @Override
    public int edit(MultiQuestion multiQuestion) {
        return baseMapper.updateById(multiQuestion);
    }
}
